package com.example.gulimall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.gulimall.common.constant.WareConstant;
import com.example.gulimall.common.utils.R;
import com.example.gulimall.ware.entity.PurchaseDetailEntity;
import com.example.gulimall.ware.feign.productFeignService;
import com.example.gulimall.ware.service.PurchaseDetailService;
import com.example.gulimall.ware.service.WareSkuService;
import com.example.gulimall.ware.vo.MergeVo;
import com.example.gulimall.ware.vo.PurchaseDoneVo;
import com.example.gulimall.ware.vo.PurchaseItemVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.gulimall.common.utils.PageUtils;
import com.example.gulimall.common.utils.Query;

import com.example.gulimall.ware.dao.PurchaseDao;
import com.example.gulimall.ware.entity.PurchaseEntity;
import com.example.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


/**
 * @author xiehaidong
 */
@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
@Autowired private PurchaseDetailService purchaseDetailService;
@Autowired
    private  productFeignService productFeignService;
@Autowired
private WareSkuService wareSkuService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryUnreceivePage(Map<String, Object> params) {
        LambdaQueryWrapper<PurchaseEntity> purchaseEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        purchaseEntityLambdaQueryWrapper.eq(PurchaseEntity::getStatus, WareConstant.PurchaseStatusEnum.CREATED.getCode())
                .or().eq(PurchaseEntity::getStatus,WareConstant.PurchaseStatusEnum.ASSIGNED.getCode());
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                purchaseEntityLambdaQueryWrapper
        );

        return new PageUtils(page);

    }

    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if(purchaseId==null){
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);
            purchaseId=purchaseEntity.getId();
        }
            Long finalPurchaseId=purchaseId;
            List<Long> list = mergeVo.getItems();
            List<PurchaseDetailEntity>  purchaseDetailEntityList= purchaseDetailService.getBaseMapper().selectBatchIds(list).stream().filter(purchaseDetailEntity -> {
                //未采购或者采购失败的才可以修改
                return purchaseDetailEntity.getStatus() < WareConstant.PurchaseDetailStatusEnum.BUYING.getCode() || purchaseDetailEntity.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode();
            }).map(entity -> {
                //修改状态并且采购单id
                entity.setPurchaseId(finalPurchaseId);
                entity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
                return entity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(purchaseDetailEntityList);

    }

    @Override
    public void receivePurchase(List<Long> ids) {
        if(ids==null||ids.size()==0){
            return;
        }
        List<PurchaseEntity> purchaseEntityList = ids.stream().filter(id -> {
            //确保采购单的状态是新建或者已分配
            PurchaseEntity purchaseEntity = this.getById(id);
            return purchaseEntity.getStatus() <= WareConstant.PurchaseStatusEnum.ASSIGNED.getCode();
        }).map(id -> {
            //修改采购单的状态为已领取
            PurchaseEntity purchaseEntity = this.getById(id);
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            return purchaseEntity;
        }).collect(Collectors.toList());
        this.updateBatchById(purchaseEntityList);
        List<Long> longList = purchaseEntityList.stream().map(purchaseEntity -> {
            return purchaseEntity.getId();
        }).collect(Collectors.toList());
        //修改采购单下的采购需求为正在采购中
     UpdateWrapper<PurchaseDetailEntity> purchaseDetailEntityUpdateWrapper = new UpdateWrapper<>();
        purchaseDetailEntityUpdateWrapper.lambda().in(PurchaseDetailEntity::getPurchaseId,longList);
        PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
        purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
        purchaseDetailService.update(purchaseDetailEntity,purchaseDetailEntityUpdateWrapper);
    }

    @Override
    @Transactional
    public void donePurchase(PurchaseDoneVo purchaseDoneVo) {
        List<PurchaseItemVo> items = purchaseDoneVo.getItems();
        ArrayList<PurchaseDetailEntity> purchaseDetailEntities = new ArrayList<>();
        boolean flag=true;
        for (PurchaseItemVo item : items) {
            PurchaseDetailEntity purchaseDetailEntity = purchaseDetailService.getById(item.getItemId());
            //更新采购需求状态
            purchaseDetailEntity.setStatus(item.getStatus());
            //采购需求失败
            if(item.getStatus()==WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                    flag=false;

            }else{
                //根据采购需求状态，更新库存
                String skuName="";
                try{
                    R info = productFeignService.info(purchaseDetailEntity.getSkuId());
                    if(info.getCode()==0){
                       Map<String,Object> skuInfo = (Map<String, Object>) info.get("skuInfo");
                        skuName = (String) skuInfo.get("skuName");
                    }
                }catch (Exception e){
                }
                //更新库存
                wareSkuService.addStock(purchaseDetailEntity.getSkuId(),purchaseDetailEntity.getWareId(),skuName,purchaseDetailEntity.getSkuNum());

            }
            purchaseDetailEntities.add(purchaseDetailEntity);
        }
      //保存采购需求
        purchaseDetailService.updateBatchById(purchaseDetailEntities);
        //根据采购需求状态，更新采购单的状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseDoneVo.getId());
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode():WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        this.updateById(purchaseEntity);
    }


}
